# -*- coding: utf-8 *-*
import pygame
from twisted.internet import reactor
from src.handler.event import EventHandler
from src.handler.sprite import SpriteHandler
from src.handler.keyboard import KeyboardHandler
from src.handler.mouse import MouseHandler
from src.helper.mouse import MouseHelper
from src.display.viewport import Viewport
from src.event.window import WindowUpdateEvent, WindowDrawLoadingScreenEvent


class Window:
    def __init__(self, width, height, flags, client):
        self.surface = pygame.display.set_mode((width, height), flags, 32)
        self.width = width
        self.height = height
        self.flags = flags
        self.client = client
        self.viewport = Viewport(self.client)

    def update(self):
        KeyboardHandler.handle(pygame.key.get_pressed(), self.client)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.client.autosave()
                reactor.stop()
            if event.type == pygame.KEYUP:
                KeyboardHandler.handleUp(event.key, self.client)
            if event.type == pygame.MOUSEBUTTONDOWN:
                mx, my = pygame.mouse.get_pos()
                if event.button == 3:
                    MouseHelper.raytraceClick(self.client.world, mx, my, self.viewport.x, self.viewport.y)
                if event.button == 1:
                    MouseHandler.handle(event.button, self.client)
                if event.button == 4:
                    MouseHandler.handleWheelUp(self.client)
                if event.button == 5:
                    MouseHandler.handleWheelDown(self.client)
            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    MouseHandler.handleUp(event.button, self.client)

        self.surface.fill((0,0,0))
        if self.viewport is not None:
            self.viewport.update()
        else:
            sprite = SpriteHandler.get("logo")
            if sprite is not None:
                self.client.window.surface.blit(sprite, (0, 0))
                EventHandler.post(WindowDrawLoadingScreenEvent(self))
        EventHandler.post(WindowUpdateEvent(self))
        pygame.display.update()
